package com.bidianying.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import redis.clients.jedis.ShardedJedisPool;

import com.bidianying.dao.GewaraDao;
import com.bidianying.dao.TaobaoDao;
import com.bidianying.util.JsonUtil;
import com.bidianying.util.LoadProperties;
import com.bidianying.util.RedisUtils;


@Service
public class TaobaoService {
	
	@Autowired
	private GewaraDao gewaraDao;
	@Autowired
	private TaobaoDao taobaoDao;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ShardedJedisPool shardedJedisPool;
	
	public static void main(String[] args) {
		RestTemplate restTemplate = new RestTemplate();
		String ajaxUrl = "http://dianying.taobao.com/showDetailSchedule.htm?showId=5&cinemaId=5950&date=2015-07-15&regionName=&n_s=new";
		HttpHeaders requestHeaders = new HttpHeaders();  
		requestHeaders.set("Accept-Charset", "utf-8");  
		requestHeaders.set("Content-type", "text/xml; charset=utf-8");
		HttpEntity<String> entity = new HttpEntity<String>(null, requestHeaders);
		ResponseEntity<String> resultStr = restTemplate.exchange(ajaxUrl, HttpMethod.GET, entity, String.class);
		Document doc = Jsoup.parse(resultStr.getBody());
		if(doc == null){
			System.out.println("doc null");
		}
		Element hall_table = doc.select("table").first();
		if(hall_table == null){
			System.out.println("hall_table null");
		}
		Elements trs = hall_table.select("tbody").first().select("tr");
		for(Element ele : trs){
			String showTime = ele.select(".hall-time").first().select("em").text();
			String opiPrice = ele.select(".hall-price").first().select("em").text();
			String href = ele.select(".seat-btn").first().attr("href");
			System.out.println(showTime);
			System.out.println(opiPrice);
			System.out.println(href);
		}
	}
	
	//根据电影id和影院id。获取价格和购票链接
	public Map<String,Map<String,String>> getPriceHref(String fyrq,String movieId,String cinemaId){
		Map<String,Map<String,String>> resultMap = new HashMap<String,Map<String,String>>();
		String ajaxUrl = "http://dianying.taobao.com/showDetailSchedule.htm?showId="+movieId+"&cinemaId="+cinemaId+"&date="+fyrq+"&regionName=&n_s=new";
		try{
			HttpHeaders requestHeaders = new HttpHeaders();  
			requestHeaders.set("Accept-Charset", "utf-8");  
			requestHeaders.set("Content-type", "text/xml; charset=utf-8");
			HttpEntity<String> entity = new HttpEntity<String>(null, requestHeaders);
			ResponseEntity<String> resultStr = restTemplate.exchange(ajaxUrl, HttpMethod.GET, entity, String.class);
			Document doc = Jsoup.parse(resultStr.getBody());
			if(doc == null){
				return resultMap;
			}
			Element hall_table = doc.select("table").first();
			if(hall_table == null){
				return resultMap;
			}
			Elements trs = hall_table.select("tbody").first().select("tr");
			for(Element ele : trs){
				String showTime = ele.select(".hall-time").first().select("em").text();
				String opiPrice = ele.select(".hall-price").first().select("em").text();
				String href = ele.select(".seat-btn").first().attr("href");
				if(href == null){
					return resultMap;
				}
				Map<String,String> map = new HashMap<String,String>();
				map.put("href", href);
				map.put("opiPrice", opiPrice);
				resultMap.put(showTime, map);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
	}
	
	
	public int saveTaobaoCinemaInfo(){
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("name", "北京");
//		jsonObject.put("pinyin", "beijing");
//		jsonObject.put("code", "110100");
//		JSONArray jsonArray = new JSONArray();
//		jsonArray.add(jsonObject);
		
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		
		JSONArray jsonArray = gewaraDao.getCity();
		
		
		String baseUrl = "http://dianying.taobao.com/cinemaList.htm?n_s=new";
		for(int j = 0;j<jsonArray.size();j++){
			JSONObject obj = jsonArray.getJSONObject(j);
			String url = baseUrl;
			if(obj.getString("name").equals("深圳")){
				continue;
			}
			if(obj.getString("code") == null || obj.getString("code").equals("")){
				continue;
			}
			System.out.println("查找城市--"+obj.getString("name"));
			try {
				Document doc = Jsoup.connect(url).cookie("tb_city", obj.getString("code")).get();
				System.out.println(obj.getString("code"));
				int count = Integer.valueOf(doc.select(".count").first().text());
				System.out.println("影院数量---"+count);
				if(count !=0&count <= 10){
					Elements elements = doc.select(".detail-middle");
					for(Element ele : elements){
						Element h4A = ele.select("h4").first().select("a").first();
						String href = h4A.attr("href");
						String cinemaName = h4A.text();
						String limitAddress = ele.select(".limit-address").first().text();
						String telephone = ele.select(".middle-p").first().select(".middle-p-list").eq(1).text();
						String[] hrefArray = href.split("\\?");
						String params = hrefArray[1];
						String[] paramsArray = params.split("&");
						String cinemaIdParam = paramsArray[0];
						String[] cinemaIdParamArray = cinemaIdParam.split("=");
						String cinemaId = cinemaIdParamArray[1];
						Map<String,String> map = new HashMap<String,String>();
						map.put("cinemaId", cinemaId);
						map.put("cinemaName", cinemaName);
						map.put("limitAddress", limitAddress);
						map.put("telephone", telephone);
						map.put("cityPinyin", obj.getString("pinyin"));
						map.put("href", href);
						list.add(map);
						Thread.sleep(1000);
					}
				}else if(count !=0 & count >10){
					for(int i = 0;i<=count/10;i++){
						String ajaxUrl = "http://dianying.taobao.com/ajaxCinemaList.htm?page="+(i+1)+"&regionName=&cinemaName=&pageSize=10&pageLength=9&sortType=0&n_s=new";
						HttpHeaders requestHeaders = new HttpHeaders();  
						requestHeaders.set("Accept-Charset", "utf-8");  
						requestHeaders.set("Content-type", "text/xml; charset=utf-8");
						requestHeaders.add("Cookie", "tb_city="+obj.getString("code"));
						HttpEntity<String> entity = new HttpEntity<String>(null, requestHeaders);
						ResponseEntity<String> resultStr = restTemplate.exchange(ajaxUrl, HttpMethod.GET, entity, String.class);
						if(resultStr.getStatusCode().value() != 200){
							continue;
						}
						if(resultStr.getBody() == null){
							continue;
						}
						Document docAjax = Jsoup.parse(resultStr.getBody());
						Elements elements = docAjax.select(".detail-middle");
						for(Element ele : elements){
							Element h4A = ele.select("h4").first().select("a").first();
							String href = h4A.attr("href");
							String cinemaName = h4A.text();
							String limitAddress = ele.select(".limit-address").first().text();
							String telephone = ele.select(".middle-p").first().select(".middle-p-list").eq(1).text();
							String[] hrefArray = href.split("\\?");
							String params = hrefArray[1];
							String[] paramsArray = params.split("&");
							String cinemaIdParam = paramsArray[0];
							String[] cinemaIdParamArray = cinemaIdParam.split("=");
							String cinemaId = cinemaIdParamArray[1];
							Map<String,String> map = new HashMap<String,String>();
							map.put("cinemaId", cinemaId);
							map.put("cinemaName", cinemaName);
							map.put("limitAddress", limitAddress);
							map.put("telephone", telephone);
							map.put("cityPinyin", obj.getString("pinyin"));
							map.put("href", href);
							list.add(map);
						}
						Thread.sleep(1000);
					}
				}
			} catch (Exception e) {
				System.out.println("出错误城市-----"+obj.getString("name"));
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}
		System.out.println("影院总数量----"+list.size());
		return taobaoDao.saveTaobaoCinemaInfo(list);
	}
	//获取淘宝的电影名称并存入表
	public int saveTaobaoMovieInfo(){
		Map<String,String> gewaraMovieMap = gewaraDao.getAllGewaraMovieInfo();
		Map<String,String> taobaoMovieMap = new HashMap<String,String>();
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		String url = "http://dianying.taobao.com/showList.htm?n_s=new";
		try {
			Document doc = Jsoup.connect(url).cookie("tb_city", "440300").get();
			Element tab_movie_list = doc.getElementsByClass("tab-movie-list").first();
			Elements movie_card_wrap = tab_movie_list.getElementsByClass("movie-card-wrap");
			for(Element ele : movie_card_wrap){
				String href = ele.select(".movie-card-buy").first().attr("href");
				String movieName = ele.select(".movie-card-name").first().select("span").first().text();
				String[] hrefArray = href.split("\\?");
				String params = hrefArray[1];
				String[] paramsArray = params.split("&");
				String cinemaIdParam = paramsArray[0];
				String[] cinemaIdParamArray = cinemaIdParam.split("=");
				String showId = cinemaIdParamArray[1];
				taobaoMovieMap.put(movieName, showId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Set<String> taobaoMapKey = taobaoMovieMap.keySet();
		for(String key : taobaoMapKey){
			if(gewaraMovieMap.containsKey(key)){
				Map<String,String> map = new HashMap<String,String>();
				map.put("id", gewaraMovieMap.get(key));
				map.put("taobaoMovieId", taobaoMovieMap.get(key));
				map.put("taobaoMovieName", key);
				list.add(map);
			}
		}
		return taobaoDao.updateMovieInfoForTaobao(list);
	}
	
}
